#include<graphics.h>
#include<conio.h>
#pragma comment(lib,"Winmm.lib")
#include<stdlib.h>

#define g 9.8

//函数外全局变量定义
IMAGE img_bk,img_bd1,img_bd2,img_bar_up1,img_bar_up2,img_bar_down1,img_bar_down2;
int bird_x,bird_y;  //小鸟的坐标
int bar_x,barDown_y;
float t=1;

void startup()  //数据初始化
{
	mciSendString("open D:\\background.mp3 alias bkmusic",NULL,0,NULL);  //背景音乐
	mciSendString("play bkmusic repeat",NULL,0,NULL);  //循环播放

	initgraph(350,600);
	loadimage(&img_bk,"D:\\background.jpg");
	loadimage(&img_bd1,"D:\\bird1.jpg");
	loadimage(&img_bd2,"D:\\bird2.jpg");
	loadimage(&img_bar_up1,"D:\\bar_up1.gif");
	loadimage(&img_bar_up2,"D:\\bar_up2.gif");
	loadimage(&img_bar_down1,"D:\\bar_down1.gif");
	loadimage(&img_bar_down2,"D:\\bar_down2.gif");
	bird_x=40;
	bird_y=300;
	bar_x=150;
	barDown_y=500;
	BeginBatchDraw();
	
}

void show()  //显示画面
{
	putimage(0,0,&img_bk);  //显示背景
	putimage(bar_x,barDown_y-750,&img_bar_up1,NOTSRCERASE);  //显示上一半障碍物
	putimage(bar_x,barDown_y-750,&img_bar_up2,SRCINVERT);
	putimage(bar_x,barDown_y,&img_bar_down1,NOTSRCERASE);  //显示下一半障碍物
	putimage(bar_x,barDown_y,&img_bar_down2,SRCINVERT);
	putimage(bird_x,bird_y,&img_bd1,NOTSRCERASE);  //显示小鸟
	putimage(bird_x,bird_y,&img_bd2,SRCINVERT);
	FlushBatchDraw();
	Sleep(50);
}
void updateWithoutInput()  //与用户输入无关的更新
{
	if(bird_y<580)
		bird_y=bird_y+0.5*g*t*t*0.01;
	if(bar_x>-150)
		bar_x=bar_x-3;
	else
	{
		bar_x=350;
		
		int randPosition=rand()%6;
		if(randPosition<2)
			randPosition=randPosition+3;
		barDown_y=100*randPosition;
	}
	t++;
}
void updateWithInput()  //与用户输入有关的更新
{
	char input;
	if (kbhit())  //判断是否有输入
	{
		input=getch();
		if(input==' '&&bird_y>20)
		{
			bird_y=bird_y-30;
			t=1;
			
			mciSendString("close jpmusic",NULL,0,NULL);  //先把前一次的音乐关掉
			mciSendString("open D:\\Jump.mp3 alias jpmusic",NULL,0,NULL);  //打开音乐
			mciSendString("play jpmusic",NULL,0,NULL);  //仅播放一次
			
		}
	}
}

void gameover()
{
	EndBatchDraw();
	getch();
	closegraph();
}

int main()
{	
	startup(); //数据初始化
	
	while(1)  //游戏循环执行
	{
		show();  //显示画面
		updateWithoutInput();  //与用户输入无关的更新
		updateWithInput();  //与用户输入有关的更新
	}
	gameover();
	return 0;
}